package com.byx.imclientutil.netty;

import com.byx.imclientutil.protobuf.ChatMessageProtobuf;

import io.netty.channel.ChannelHandlerContext;

/**
 * HeartBeatTask
 *
 * @author Superb
 * @date 2021/4/4 17:25
 */
public class HeartBeatTask implements Runnable {
    private ChannelHandlerContext channelHandlerContext;
    private NettyWebSocketClientImpl imService;

    public HeartBeatTask(ChannelHandlerContext channelHandlerContext, NettyWebSocketClientImpl imService) {
        this.channelHandlerContext = channelHandlerContext;
        this.imService = imService;
    }

    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {
        if (channelHandlerContext.channel().isActive()){
            ChatMessageProtobuf.Msg heartBeatMsg = imService.getHeartbeatMsg();
            if (heartBeatMsg == null){
                return;
            }
            System.out.println("发送心跳消息，"+heartBeatMsg);
            imService.sendMessage(heartBeatMsg);
        }
    }
}
